﻿using System.Collections.Concurrent;
using System.Reflection;

namespace Easy.Core;

public static class EnumExtension
{
    /// <summary>
    /// 缓存
    /// </summary>
    private static readonly ConcurrentDictionary<string, string> EnumDic = new();

    /// <summary>
    /// 获取枚举上定义的Description
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string Description(this Enum value)
    {
        Type type = value.GetType();
        string vs = value.ToString(), key = $"{type.FullName}_{vs}";
        if (EnumDic.TryGetValue(key, out var description))
        {
            return description;
        }

        FieldInfo fieldInfo = type.GetField(vs);
        if (fieldInfo != null && fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() is DescriptionAttribute descriptionAttribute)
        {
            string desc = descriptionAttribute.Description;
            EnumDic.TryAdd(key, desc);
            return desc;
        }

        return string.Empty;
    }
}